﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Threading;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using Microsoft.Advertising.Mobile.UI;
using MTGScore.Resources;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Phone.Tasks;

namespace MTGScore
{
    public enum TimerStatus
    {
        Running,
        Stopped,
        Paused
    }

    public partial class MainPage : PhoneApplicationPage
    {
        static int LIFE_MIN_VALUE = -10000;
        static int LIFE_MAX_VALUE = 10000;
        static int CENTER_MIN_VALUE = 0;
        static int CENTER_MAX_VALUE = 999;
        static int MANA_MIN_VALUE = 0;
        static int MANA_MAX_VALUE = 99;
        static int MOMENT_TIME_INTERVAL_MAX_VALUE_MILLISECONDS = 1300;
        static int SECONDS_BETWEEN_HISTORY_CREATION = 5;

        SavedOptions savedOptions;
        int player1_life, player2_life;
        int player1_center, player2_center;
        Timer timer;
        TimeSpan timeSpan;
        TimeSpan dice_timeSpan;
        //bool first_loading;
        // Constructor

        int mana0;
        int mana1;
        int mana2;
        int mana3;
        int mana4;
        int mana5;
        int mana6;
        TimerStatus timer_status;
        bool start_timer_on_resume;
        bool is_resumed = false;
        SavedMatch match;
        SearchResult currentResult;
        int current_page = -1;
        bool isTrial;
        public MainPage()
        {
            //first_loading = true;
            InitializeComponent();

            // Set the data  context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            SupportedOrientations = SupportedPageOrientation.Portrait;
            //SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;

            //OrientationChanged += new EventHandler<OrientationChangedEventArgs>(MainPage_OrientationChanged);

            savedOptions = Storage.LoadSavedOptions();

            if (savedOptions.allow_screen_off)
                PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
            match = new SavedMatch();

            currentResult = new SearchResult();
            isTrial = App.isTrial();


            helps = Helps.GetHelps();
            for (int i = 0; i < helps.Count; i++)
            {
                var h = helps[i];
                Helps_List.Items.Add(new ListBoxItem() { Content = h.name, FontSize = 30 });
            }

            try
            {
                var occ = Research.LoadUtilizations() + 1;
                new Thread(new ThreadStart(() =>
                {
                    Research.getHTML(Research.GetUtilizationUrl(occ, App.isTrial()),
                        (s) =>
                        {
                            Research.DeleteUtilizations();
                        },
                        () =>
                        {
                            Research.SaveUtilizations(occ);
                        });
                })).Start();
            }
            catch { }
        }


        void SetTrialMode()
        {
            if (isTrial)
            {
                //PivotControl.Items.Remove(SearchPivot_Name);
                //PivotControl.Items.Remove(SettingsPivot_Name);
                PivotControl.Items.Remove(GuidePivot_Name);
                Play_Button.Visibility = System.Windows.Visibility.Collapsed;
                Trial_Text_Area.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                AdControl.Visibility = System.Windows.Visibility.Collapsed;
                AdControlGrid.Visibility = System.Windows.Visibility.Collapsed;
                Grid.SetRowSpan(PivotControl, 2);
            }
        }

        //void MainPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        //{
        //    var a = 1;
        //    a = 1;


        //}
        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
            //ClearGame(true);

            //TimerType.SelectionMode = SelectionMode.Single;
            //LoadSavedOptions();
            //SaveOptionsState();


            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton credits = new ApplicationBarIconButton() { Text = Strings.Credits, IsEnabled = true };

            if (App.CurrentTheme == App.Theme.Dark)
                credits.IconUri = new Uri("\\Images\\dark\\appbar.questionmark.rest.png", UriKind.Relative);
            else
                credits.IconUri = new Uri("\\Images\\light\\appbar.questionmark.rest.png", UriKind.Relative);
            credits.Click += OpenCredits_Button_Click;
            ApplicationBar.Buttons.Add(credits);

            if (!isTrial)
            {
                ApplicationBarIconButton settings = new ApplicationBarIconButton() { Text = Strings.Settings, IsEnabled = true };

                if (App.CurrentTheme == App.Theme.Dark)
                    settings.IconUri = new Uri("\\Images\\dark\\appbar.feature.settings.rest.png", UriKind.Relative);
                else
                    settings.IconUri = new Uri("\\Images\\light\\appbar.feature.settings.rest.png", UriKind.Relative);
                settings.Click += OpenSettings_Button_Click;
                ApplicationBar.Buttons.Add(settings);
            }



            CenterName_TextArea.Text = savedOptions.center_value;

            if (savedOptions.allow_Timer)
                SetTimerOptions(true);
            else
                SetTimerOptions(false);

            if (App.CurrentTheme == App.Theme.Dark)
            {
                Play_Button.Source = new BitmapImage(new Uri("Images\\dark\\play.png", UriKind.Relative));
                Pause_Button.Source = new BitmapImage(new Uri("Images\\dark\\pause.png", UriKind.Relative));
                Stop_Button.Source = new BitmapImage(new Uri("Images\\dark\\stop.png", UriKind.Relative));
                //Restart_Button.Source = new BitmapImage(new Uri("Images/dark\\restart.png", UriKind.Relative));
                //Play_Button.Source = "Images\dark\play.png";
            }
            else
            {

                Play_Button.Source = new BitmapImage(new Uri("Images\\light\\play.png", UriKind.Relative));
                Pause_Button.Source = new BitmapImage(new Uri("Images\\light\\pause.png", UriKind.Relative));
                Stop_Button.Source = new BitmapImage(new Uri("Images\\light\\stop.png", UriKind.Relative));
                //Restart_Button.Source = new BitmapImage(new Uri("Images\\light\\restart.png", UriKind.Relative));
            }
            if (start_timer_on_resume)
            {
                if (timer != null)
                {
                    timer.Dispose();
                }
                timer = new Timer(new TimerCallback(Timer_Callback), null, 0, 1000);

            }
            else
            {
                timer_status = TimerStatus.Stopped;
            }
            SetTimerControls();
            if (current_page >= 0 && current_page < 6)
                PivotControl.SelectedIndex = current_page;
            else
                if (!is_resumed && savedOptions.first_page >= 0 && savedOptions.first_page < 6)
                {
                    PivotControl.SelectedIndex = savedOptions.first_page;

                    //if (savedOptions.first_page == 0)
                    //    FirstPageChoose_Area.Text = Strings.Match;
                    //else if (savedOptions.first_page == 1)
                    //    FirstPageChoose_Area.Text = Strings.Mana;
                    //else if (savedOptions.first_page == 2)
                    //    FirstPageChoose_Area.Text = Strings.History;
                    //else if (savedOptions.first_page == 3)
                    //    FirstPageChoose_Area.Text = Strings.SearchCards;
                    //else if (savedOptions.first_page == 4)
                    //    FirstPageChoose_Area.Text = Strings.Helps;
                    //else if (savedOptions.first_page == 5)
                    //    FirstPageChoose_Area.Text = Strings.Settings;
                    //else
                    //    FirstPageChoose_Area.Text = Strings.Match;
                }
            SaveMoment(false);
            UpdateTextAreas();
            CreateApplicationBar();
            SetTrialMode();

        }



        void SetTimerOptions(bool on)
        {
            if (on && !isTrial)
            {
                //main page
                timer_area.Visibility = System.Windows.Visibility.Visible;
                Play_Button.Visibility = System.Windows.Visibility.Visible;


            }
            else
            {
                //main page
                timer_area.Visibility = System.Windows.Visibility.Collapsed;
                Play_Button.Visibility = System.Windows.Visibility.Collapsed;
                Pause_Button.Visibility = System.Windows.Visibility.Collapsed;
                //Restart_Button.Visibility = System.Windows.Visibility.Collapsed;
                Stop_Button.Visibility = System.Windows.Visibility.Collapsed;


            }
        }


        private void ClearGame(bool clear_timer)
        {
            //if (match.savedMoments == null || match.savedMoments.Count == 0)
            //{
            if (MessageBox.Show(Strings.CrearGameConfirm, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                return;
            //CenterName_TextArea.Text = Strings.Infect;
            //Player1Name_TextArea.Text = Strings.Player_1;
            //Player2Name_TextArea.Text = Strings.Player_2;
            player1_life = 20;
            player2_life = 20;
            player1_center = 0;
            player2_center = 0;
            My_Life.Text = "" + player1_life;
            Opponent_Life.Text = "" + player2_life;
            My_Center_Area.Text = "" + player1_center;
            Opponent_Center_Area.Text = "" + player2_center;
            mana0 = 0;
            mana1 = 0;
            mana2 = 0;
            mana3 = 0;
            mana4 = 0;
            mana5 = 0;
            mana6 = 0;

            if (clear_timer)
            {
                timer_status = TimerStatus.Stopped;
                if (!isTrial)
                    SetTimerControls();
                if (timer != null)
                {
                    timer.Dispose();
                }
                if (savedOptions.allow_Timer)
                {
                    timer = new Timer(new TimerCallback(Timer_Callback), null, 0, 1000);
                    if (savedOptions.timerType == TimerType.Decreasing)
                        timeSpan = savedOptions.timeSpan;
                    else
                        timeSpan = TimeSpan.Zero;
                    timer_area.Text = timeSpan.ToString();
                }
            }
            match.savedMoments.Clear();
            SaveMoment(false);
        }
        private void SaveOptionsState()
        {
            //if (first_loading)
            Storage.SaveSavedOptions(savedOptions);
        }


        private void Add_My_Life_Click(object sender, RoutedEventArgs e)
        {
            player1_life++;
            player1_life = Math.Min(player1_life, LIFE_MAX_VALUE);
            My_Life.Text = "" + player1_life;
            SaveMoment(false);
            CheckVictoryConditions();
        }

        private void Clear_Game_Click(object sender, RoutedEventArgs e)
        {
            ClearGame(false);
        }

        private void Subtrack_My_Life_Click(object sender, RoutedEventArgs e)
        {
            player1_life--;
            if (savedOptions.allow_center_end_game)
                player1_life = Math.Max(0, player1_life);
            else
                player1_life = Math.Max(player1_life, LIFE_MIN_VALUE);
            My_Life.Text = "" + player1_life;
            SaveMoment(false);
            CheckVictoryConditions();
        }

        private void Add_Opponent_Life_Click(object sender, RoutedEventArgs e)
        {
            player2_life++;
            player2_life = Math.Min(player2_life, LIFE_MAX_VALUE);
            Opponent_Life.Text = "" + player2_life;
            SaveMoment(false);
            CheckVictoryConditions();
        }

        private void Add_My_Center_Click(object sender, RoutedEventArgs e)
        {
            player1_center++;
            player1_center = Math.Min(player1_center, CENTER_MAX_VALUE);
            My_Center_Area.Text = "" + player1_center;
            SaveMoment(false);
            CheckVictoryConditions();
        }
        private void Add_Opponent_Center_Click(object sender, RoutedEventArgs e)
        {
            player2_center++;
            player2_center = Math.Min(player2_center, CENTER_MAX_VALUE);
            Opponent_Center_Area.Text = "" + player2_center;
            SaveMoment(false);
            CheckVictoryConditions();
        }
        private void Sub_My_Center_Click(object sender, RoutedEventArgs e)
        {
            player1_center--;
            player1_center = Math.Max(player1_center, CENTER_MIN_VALUE);
            My_Center_Area.Text = "" + player1_center;
            SaveMoment(false);
            CheckVictoryConditions();
        }
        private void Sub_Opponent_Center_Click(object sender, RoutedEventArgs e)
        {
            player2_center--;
            if (savedOptions.allow_center_end_game)
                player2_center = Math.Max(0, player2_center);
            else
                player2_center = Math.Max(player2_center, CENTER_MIN_VALUE);
            Opponent_Center_Area.Text = "" + player2_center;
            SaveMoment(false);
            CheckVictoryConditions();
        }
        private void Subtrack_Opponent_Life_Click(object sender, RoutedEventArgs e)
        {
            player2_life--;
            player2_life = Math.Max(player2_life, LIFE_MIN_VALUE);
            Opponent_Life.Text = "" + player2_life;
            SaveMoment(false);
            CheckVictoryConditions();
        }
        private void Open_Dice_Simulation_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/DicePage.xaml", UriKind.Relative));
        }



        //private void CountDownToggle_Checked(object sender, RoutedEventArgs e)
        //{
        //    if (savedOptions.countDown == true)
        //        return;
        //    savedOptions.countDown = true;
        //    SaveOptionsState();
        //}
        //private void CountDownToggle_Unchecked(object sender, RoutedEventArgs e)
        //{
        //    if (savedOptions.countDown == false)
        //        return;
        //    savedOptions.countDown = false;
        //    SaveOptionsState();
        //}

        //private void TimePicker_LostFocus(object sender, RoutedEventArgs e)
        //{
        //    if (savedOptions.timeSpan == TimePicker.Value.Value)
        //        return;

        //    savedOptions.timeSpan = TimePicker.Value.Value;
        //    SaveOptionsState();
        //}
        //private void AlertTimePicker_LostFocus(object sender, RoutedEventArgs e)
        //{
        //    if (savedOptions.alertTimeSpan == AlertTimePicker.Value.Value)
        //        return;

        //    savedOptions.alertTimeSpan = AlertTimePicker.Value.Value;
        //    SaveOptionsState();
        //}
        private void MyLife_LostFocus(object sender, RoutedEventArgs e)
        {
            //my_life = Int16.Parse(My_Life.Text);
            Int32 a;
            if (Int32.TryParse(My_Life.Text, out a))
                player1_life = Math.Max(Math.Min(a, LIFE_MAX_VALUE), LIFE_MIN_VALUE);

            My_Life.Text = "" + player1_life;
        }
        private void CenterText_LostFocus(object sender, RoutedEventArgs e)
        {
            //my_life = Int16.Parse(My_Life.Text);
            savedOptions.center_value = CenterName_TextArea.Text;
            SaveOptionsState();
        }
        private void OpponentLife_LostFocus(object sender, RoutedEventArgs e)
        {
            Int32 a;
            if (Int32.TryParse(Opponent_Life.Text, out a))
                player2_life = Math.Max(Math.Min(a, LIFE_MAX_VALUE), LIFE_MIN_VALUE);

            Opponent_Life.Text = "" + player2_life;
        }


        private void MyCenter_LostFocus(object sender, RoutedEventArgs e)
        {
            Int32 a;
            if (Int32.TryParse(My_Center_Area.Text, out a))
                player1_center = Math.Max(Math.Min(a, CENTER_MAX_VALUE), CENTER_MIN_VALUE);

            My_Center_Area.Text = "" + player1_center;
        }
        private void OpponentCenter_LostFocus(object sender, RoutedEventArgs e)
        {
            Int32 a;
            if (Int32.TryParse(Opponent_Center_Area.Text, out a))
                player2_center = Math.Max(Math.Min(a, CENTER_MAX_VALUE), CENTER_MIN_VALUE);

            Opponent_Center_Area.Text = "" + player2_center;
        }


        private void CheckVictoryConditions()
        {
            if (savedOptions.allow_center_end_game)
            {
                bool end_game = false;
                if (player1_life <= 0)
                {
                    MessageBox.Show(Strings.Win + " " + Player2Name_TextArea.Text + "!");
                    end_game = true;
                }
                else if (player2_life <= 0)
                {
                    MessageBox.Show(Strings.Win + " " + Player1Name_TextArea.Text + "!");
                    end_game = true;
                }
                else if (player1_center >= savedOptions.center_max_value)
                {
                    MessageBox.Show(Strings.Win + " " + Player2Name_TextArea.Text + " " + Strings.For + " " + CenterName_TextArea.Text + "!");
                    end_game = true;
                    player1_center = savedOptions.center_max_value;
                }
                else if (player2_center >= savedOptions.center_max_value)
                {
                    MessageBox.Show(Strings.Win + " " + Player1Name_TextArea.Text + " " + Strings.For + " " + CenterName_TextArea.Text + "!");
                    end_game = true;
                    player2_center = savedOptions.center_max_value;
                }

                if (end_game)
                {
                    UpdateTextAreas();
                    timer_status = TimerStatus.Stopped;
                    SetTimerControls();
                }
            }
        }
        private void CheckTimerConditions()
        {
            if (savedOptions.timerType == MTGScore.TimerType.Decreasing)
            {
                if (timeSpan <= TimeSpan.Zero)
                {
                    timer_status = TimerStatus.Stopped;
                    timeSpan = TimeSpan.Zero;
                    timer_area.Text = timeSpan.ToString();
                    SetTimerControls();


                    if (savedOptions.alert_end_time)
                    {
                        var s = Strings.Win;

                        if (player1_life < player2_life)
                            s += Player2Name_TextArea.Text;
                        else if (player1_life > player2_life)
                            s += Player1Name_TextArea.Text;
                        else
                            s = Strings.DrawGame;
                        s += "!";

                        MessageBox.Show(s, Strings.TimesUp, MessageBoxButton.OK);



                    }
                    return;
                }
                var a = timeSpan - savedOptions.alertTimeSpan;
                if (savedOptions.alert_time && a == TimeSpan.Zero)
                {
                    //savedOptions.alert_time = false;
                    //AlertTimePicker.Visibility = System.Windows.Visibility.Collapsed;
                    //AlertTimePickerText.Visibility = System.Windows.Visibility.Collapsed;
                    MessageBox.Show(Strings.Alert, Strings.TimedAlert, MessageBoxButton.OK);
                    return;
                }
            }

        }

        void UpdateTextAreas()
        {
            My_Life.Text = "" + player1_life;
            Opponent_Life.Text = "" + player2_life;
            My_Center_Area.Text = "" + player1_center;
            Opponent_Center_Area.Text = "" + player2_center;

            Mana0Area.Text = "" + mana0;
            Mana1Area.Text = "" + mana1;
            Mana2Area.Text = "" + mana2;
            Mana3Area.Text = "" + mana3;
            Mana4Area.Text = "" + mana4;
            Mana5Area.Text = "" + mana5;
            Mana6Area.Text = "" + mana6;

            timer_area.Text = timeSpan.ToString();
        }


        #region EVENTI_MANA
        private int ComputeMana(int mana, int delta, TextBox button)
        {
            mana += delta;
            if (delta > 0)
                mana = Math.Min(mana, MANA_MAX_VALUE);
            else
                mana = Math.Max(mana, MANA_MIN_VALUE);
            button.Text = "" + mana;
            return mana;
        }

        private void Mana_Add0_Click(object sender, RoutedEventArgs e)
        {
            mana0 = ComputeMana(mana0, 1, Mana0Area);
        }
        private void Mana_Add1_Click(object sender, RoutedEventArgs e)
        {
            mana1 = ComputeMana(mana1, 1, Mana1Area);
        }
        private void Mana_Add2_Click(object sender, RoutedEventArgs e)
        {
            mana2 = ComputeMana(mana2, 1, Mana2Area);
        }
        private void Mana_Add3_Click(object sender, RoutedEventArgs e)
        {
            mana3 = ComputeMana(mana3, 1, Mana3Area);
        }
        private void Mana_Add4_Click(object sender, RoutedEventArgs e)
        {
            mana4 = ComputeMana(mana4, 1, Mana4Area);
        }
        private void Mana_Add5_Click(object sender, RoutedEventArgs e)
        {
            mana5 = ComputeMana(mana5, 1, Mana5Area);
        }
        private void Mana_Add6_Click(object sender, RoutedEventArgs e)
        {
            mana6 = ComputeMana(mana6, 1, Mana6Area);
        }

        private void Mana_Sub0_Click(object sender, RoutedEventArgs e)
        {
            mana0 = ComputeMana(mana0, -1, Mana0Area);
        }
        private void Mana_Sub1_Click(object sender, RoutedEventArgs e)
        {
            mana1 = ComputeMana(mana1, -1, Mana1Area);
        }
        private void Mana_Sub2_Click(object sender, RoutedEventArgs e)
        {
            mana2 = ComputeMana(mana2, -1, Mana2Area);
        }
        private void Mana_Sub3_Click(object sender, RoutedEventArgs e)
        {
            mana3 = ComputeMana(mana3, -1, Mana3Area);
        }
        private void Mana_Sub4_Click(object sender, RoutedEventArgs e)
        {
            mana4 = ComputeMana(mana4, -1, Mana4Area);
        }
        private void Mana_Sub5_Click(object sender, RoutedEventArgs e)
        {
            mana5 = ComputeMana(mana5, -1, Mana5Area);
        }
        private void Mana_Sub6_Click(object sender, RoutedEventArgs e)
        {
            mana6 = ComputeMana(mana6, -1, Mana6Area);
        }

        private int CheckManaValue(int mana, TextBox box)
        {
            var s = box.Text;
            try
            {
                Int32 val = Int32.Parse(box.Text);
                val = Math.Min(99, val);
                val = Math.Max(-99, val);
                box.Text = "" + val;
                return val;
            }
            catch (Exception e)
            {
                e.ToString();
                box.Text = "" + mana;
                return mana;
            }
        }
        private void Mana0Area_LostFocus(object sender, RoutedEventArgs e)
        {
            mana0 = CheckManaValue(mana0, Mana0Area);

        }
        private void Mana1Area_LostFocus(object sender, RoutedEventArgs e)
        {
            mana1 = CheckManaValue(mana1, Mana1Area);
        }
        private void Mana2Area_LostFocus(object sender, RoutedEventArgs e)
        {
            mana2 = CheckManaValue(mana2, Mana2Area);
        }
        private void Mana3Area_LostFocus(object sender, RoutedEventArgs e)
        {
            mana3 = CheckManaValue(mana3, Mana3Area);
        }
        private void Mana4Area_LostFocus(object sender, RoutedEventArgs e)
        {
            mana4 = CheckManaValue(mana4, Mana4Area);
        }
        private void Mana5Area_LostFocus(object sender, RoutedEventArgs e)
        {
            mana5 = CheckManaValue(mana5, Mana5Area);
        }
        private void Mana6Area_LostFocus(object sender, RoutedEventArgs e)
        {
            mana6 = CheckManaValue(mana6, Mana6Area);
        }

        private void Mana6Text_LostFocus(object sender, RoutedEventArgs e)
        {
            match.center_name = Mana6Area.Text;
        }
        #endregion



        #region EVENTI_CONTROLLO_TIMER

        private void SetTimerControls()
        {
            //Restart_Button.Visibility = System.Windows.Visibility.Collapsed;
            if (savedOptions.allow_Timer)
            {
                switch (timer_status)
                {
                    case TimerStatus.Paused:
                        Pause_Button.Visibility = System.Windows.Visibility.Collapsed;
                        Play_Button.Visibility = System.Windows.Visibility.Visible;
                        Stop_Button.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case TimerStatus.Running:
                        Pause_Button.Visibility = System.Windows.Visibility.Visible;
                        Play_Button.Visibility = System.Windows.Visibility.Collapsed;
                        Stop_Button.Visibility = System.Windows.Visibility.Visible;
                        break;
                    case TimerStatus.Stopped:
                        Pause_Button.Visibility = System.Windows.Visibility.Collapsed;
                        Play_Button.Visibility = System.Windows.Visibility.Visible;
                        Stop_Button.Visibility = System.Windows.Visibility.Collapsed;
                        break;

                }
            }
            else
            {
                Pause_Button.Visibility = System.Windows.Visibility.Collapsed;
                Play_Button.Visibility = System.Windows.Visibility.Collapsed;
                Stop_Button.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void Play_Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (timer == null)
                timer = new Timer(new TimerCallback(Timer_Callback), null, 0, 1000);

            //timeSpan = savedOptions.timeSpan;
            //timer_area.Text = timeSpan.ToString();

            timer_status = TimerStatus.Running;
            SetTimerControls();
        }

        private void Pause_Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            timer_status = TimerStatus.Paused;
            SetTimerControls();
        }

        private void Stop_Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (MessageBox.Show(Strings.StopTimer, Strings.Confirm, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                timer_status = TimerStatus.Stopped;

                if (savedOptions.timerType == MTGScore.TimerType.Increasing)
                    timeSpan = TimeSpan.Zero;
                else
                    timeSpan = savedOptions.timeSpan;
                timer_area.Text = timeSpan.ToString();

                SetTimerControls();
            }
        }

        private void Timer_Callback(object o)
        {
            if (savedOptions.allow_Timer && !isTrial)
                Dispatcher.BeginInvoke(() => UpdateTimer());
        }
        int seconds_from_last_hystory_save = 0;
        private void UpdateTimer()
        {
            seconds_from_last_hystory_save++;
            if (seconds_from_last_hystory_save >= SECONDS_BETWEEN_HISTORY_CREATION)
            {
                //History.CreateHistory(Lista, match);
                SaveMoment(false);
                seconds_from_last_hystory_save = 0;
            }

            if (!(timer_status == TimerStatus.Running))
                return;
            int val = 1;
            if (savedOptions.timerType == MTGScore.TimerType.Decreasing)
                val *= -1;
            timeSpan += new TimeSpan(0, 0, val);
            dice_timeSpan += new TimeSpan(0, 0, val);
            timer_area.Text = timeSpan.ToString();

            CheckTimerConditions();



        }


        #endregion

        #region PIVOT_CONTROL
        private void EnableIsHitTestVisible(object sender, RoutedEventArgs e)
        {
            PivotControl.IsHitTestVisible = true;
        }
        #endregion

        #region ACTIVATE_DEACTIVATE
        private TimerType prev_timer_type;
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {

            base.OnNavigatedFrom(e);
            savedOptions = Storage.LoadSavedOptions();
            if (this.State.ContainsKey("MTGSCore_SavedMatch"))
            {

                match = (SavedMatch)(this.State["MTGSCore_SavedMatch"]);

                this.State.Remove("MTGSCore_SavedMatch");
                LoadLastMoment();
                if (match.timer_status == TimerStatus.Stopped)
                    timeSpan = savedOptions.timeSpan;
                else
                    timeSpan += dice_timeSpan;

                Player1Name_TextArea.Text = match.player1_name;
                Player2Name_TextArea.Text = match.player2_name;
                timer_status = match.timer_status;
                Mana6Text.Text = match.mana6_name;

                if (match.mana_values == null || match.mana_values.Count != 7)
                    match.mana_values = new List<int>(7);

                mana0 = match.mana_values[0];
                mana1 = match.mana_values[1];
                mana2 = match.mana_values[2];
                mana3 = match.mana_values[3];
                mana4 = match.mana_values[4];
                mana5 = match.mana_values[5];
                mana6 = match.mana_values[6];

                start_timer_on_resume = true;

                SetTimerControls();

                is_resumed = true;
                if (prev_timer_type != savedOptions.timerType)
                {
                    if (savedOptions.timerType == TimerType.Decreasing)
                        timeSpan = savedOptions.timeSpan;
                    else
                        timeSpan = TimeSpan.Zero;
                    prev_timer_type = savedOptions.timerType;
                }
            }
            else
            {
                player1_life = 20;
                player2_life = 20;
                player1_center = 0;
                player2_center = 0;
                mana0 = 0;
                mana1 = 0;
                mana2 = 0;
                mana3 = 0;
                mana4 = 0;
                mana5 = 0;
                mana6 = 0;
                start_timer_on_resume = false;
                is_resumed = false;
                if (savedOptions.timerType == TimerType.Decreasing)
                    timeSpan = savedOptions.timeSpan;
                else
                    timeSpan = TimeSpan.Zero;
            }
            UpdateTextAreas();
            SetTimerControls();
            if (this.State.ContainsKey("MTGScore_CurrentResult"))
            {
                currentResult = (SearchResult)(this.State["MTGScore_CurrentResult"]);

                this.State.Remove("MTGScore_CurrentResult");

                BuildResults();
            }
            else
                currentResult = new SearchResult();
            //Results_List.Items.Clear();
            App.ViewModel.Cards.Clear();
            if (this.State.ContainsKey("MTGScore_CurrentQuery"))
            {
                current_query = (string)(this.State["MTGScore_CurrentQuery"]);

                this.State.Remove("MTGScore_CurrentQuery");
                //Results_List.Items.Clear();
                BuildResults();
            }
            else
                currentResult = new SearchResult();

            if (this.State.ContainsKey("MTGScore_CurrentPage"))
            {
                current_page = (int)(this.State["MTGScore_CurrentPage"]);
                this.State.Remove("MTGScore_CurrentPage");
            }
            else
                current_page = -1;
        }


        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {

            base.OnNavigatedTo(e);
            dice_timeSpan = TimeSpan.Zero;

            match.player1_name = Player1Name_TextArea.Text;
            match.player2_name = Player2Name_TextArea.Text;
            match.center_name = CenterName_TextArea.Text;

            match.timer_status = timer_status;
            match.mana6_name = Mana6Text.Text;

            if (match.mana_values == null || match.mana_values.Count != 7)
                match.mana_values = new List<int>(7) { 0, 0, 0, 0, 0, 0, 0 };

            match.mana_values[0] = mana0;
            match.mana_values[1] = mana1;
            match.mana_values[2] = mana2;
            match.mana_values[3] = mana3;
            match.mana_values[4] = mana4;
            match.mana_values[5] = mana5;
            match.mana_values[6] = mana6;
            prev_timer_type = savedOptions.timerType;
            SaveMoment(true);
            this.State.Add("MTGSCore_SavedMatch", match);
            if (currentResult != null && currentResult.cards.Count != 0)
                this.State.Add("MTGScore_CurrentResult", currentResult);
            this.State.Add("MTGScore_CurrentQuery", current_query);
            this.State.Add("MTGScore_CurrentPage", PivotControl.SelectedIndex);
            SaveOptionsState();
        }

        public void SaveMoment(bool auto_saved)
        {
            if (match.savedMoments == null)
                match.savedMoments = new List<SavedMoment>();
            SavedMoment newMoment = new SavedMoment(player1_life, player2_life, player1_center, player2_center,
                (isTrial ? TimeSpan.Zero : timeSpan), auto_saved);

            if (match.savedMoments.Count > 0)
            {
                var m = match.savedMoments[match.savedMoments.Count - 1];

                if (m.CompareValues(newMoment) == SavedMomentValueType.None)
                {
                    match.savedMoments.Remove(m);
                }
                else if (timer_status == TimerStatus.Running)
                {
                    TimeSpan delta;
                    if (savedOptions.timerType == MTGScore.TimerType.Increasing)

                        delta = (timeSpan - m.time_span);

                    else
                        delta = (m.time_span - timeSpan);

                    if (delta <= new TimeSpan(0, 0, 0, 0, MOMENT_TIME_INTERVAL_MAX_VALUE_MILLISECONDS))
                        match.savedMoments.Remove(m);
                    //    var a = Math.Abs((timeSpan - m.time_span).Ticks);
                    //    if (a <= MOMENT_TIME_INTERVAL_MAX_VALUE * 1000000)
                    //        match.savedMoments.Remove(m);
                }
                else
                {
                    if (match.savedMoments.Count >= 2)
                    {
                        var m_old = match.savedMoments[match.savedMoments.Count - 2];

                        var delta = m.CompareValues(newMoment);
                        var delta2 = m_old.CompareValues(newMoment);

                        if (delta == delta2)
                            match.savedMoments.Remove(m);
                    }
                }
            }

            match.savedMoments.Add(newMoment);
            //if(!auto_saved)
            //History.CreateHistory(Lista, match);
        }
        public void LoadLastMoment()
        {
            if (match.savedMoments == null || match.savedMoments.Count == 0)
                return;
            SavedMoment s = match.savedMoments[match.savedMoments.Count - 1];
            player1_life = s.player1_life;
            player2_life = s.player2_life;
            player1_center = s.player1_center;
            player2_center = s.player2_center;

            //if (!is_opened_time_picker)
            timeSpan = s.time_span;
            if (s.auto_saved)
                match.savedMoments.Remove(s);
            //is_opened_time_picker = false;
        }
        #endregion

        #region HISTORY



        private void HistorySave_Button_Click(object sender, RoutedEventArgs e)
        {
            if (match.savedMoments.Count > 1)
            {
                //BuildHistory_Button_Click(sender, e);
                match.player1_name = Player1Name_TextArea.Text;
                match.player2_name = Player2Name_TextArea.Text;
                match.center_name = CenterName_TextArea.Text;

                try
                {
                    new Thread(new ThreadStart(() =>
                    {
                        History.SaveToDisk(match);
                    })).Start();

                }
                catch (Exception) { }
                MessageBox.Show(Strings.Saved);
            }
            else
                MessageBox.Show(Strings.EmptyHistory);

        }

        private void HistoryLoad_Button_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/HistoryPage.xaml", UriKind.Relative));
        }

        //private void Lista_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    History.SelectionChange(Lista);
        //}

        //private void BuildHistory_Button_Click(object sender, RoutedEventArgs e)
        //{
        //    SaveMoment(false);
        //    match.player1_name = Player1Name_TextArea.Text;
        //    match.player2_name = Player2Name_TextArea.Text;
        //    match.center_name = CenterName_TextArea.Text;

        //    //History.CreateHistory(Lista, match);

        //    History.CreateHistory(App.ViewModel.CurrentHistory, match);

        //    BuildHistory_Button.Visibility = System.Windows.Visibility.Collapsed;
        //}



        #endregion

        private void AdControl_AdControlError(object sender, ErrorEventArgs e)
        {


        }
        List<Set> helps = new List<Set>();

        private void PivotControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            /*
            if (PivotControl.SelectedItem == GuidePivot_Name)
            {
                if (Helps_List.Items.Count == 0)
                {
                    helps = Helps.GetHelps();
                    for (int i = 0; i < helps.Count; i++)
                    {
                        var h = helps[i];
                        Helps_List.Items.Add(new ListBoxItem() { Content = h.name, FontSize = 30 });
                    }
                }
            }*/
            if (PivotControl.SelectedIndex != 2)
            {
                //Lista.Items.Clear();
                //BuildHistory_Button.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                History_Player1_Name.Text = Player1Name_TextArea.Text;
                History_Player2_Name.Text = Player2Name_TextArea.Text;
                History.CreateHistory(App.ViewModel.CurrentHistory, match);
            }
            CreateApplicationBar();
        }
        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }
        private void OpenSettings_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
        }
        private void CreateApplicationBar()
        {
            //if (isTrial)
            //{
            //    ApplicationBar.IsVisible = false;
            //    return;
            //}


            ApplicationBar.MenuItems.Clear();
            if (!isTrial && savedOptions.allow_shortcut_menu)
            {
                ApplicationBar.IsMenuEnabled = true;
                ApplicationBar.IsVisible = true;
                if (PivotControl.SelectedItem != MatchPivot_Name)
                {
                    ApplicationBarMenuItem item = new ApplicationBarMenuItem(Strings.Match);
                    item.IsEnabled = true;
                    item.Click += ApplicationBarMenuButton_Click;
                    ApplicationBar.MenuItems.Add(item);
                }
                if (PivotControl.SelectedItem != ManaPivot_Name)
                {
                    ApplicationBarMenuItem item = new ApplicationBarMenuItem(Strings.Mana);
                    item.IsEnabled = true;
                    item.Click += ApplicationBarMenuButton_Click;
                    ApplicationBar.MenuItems.Add(item);
                }
                if (PivotControl.SelectedItem != HistoryPivot_Name)
                {
                    ApplicationBarMenuItem item = new ApplicationBarMenuItem(Strings.History);
                    item.IsEnabled = true;
                    item.Click += ApplicationBarMenuButton_Click;
                    ApplicationBar.MenuItems.Add(item);
                }
                if (PivotControl.SelectedItem != SearchPivot_Name)
                {
                    ApplicationBarMenuItem item = new ApplicationBarMenuItem(Strings.SearchCards);
                    item.IsEnabled = true;
                    item.Click += ApplicationBarMenuButton_Click;
                    ApplicationBar.MenuItems.Add(item);
                }
                if (PivotControl.SelectedItem != GuidePivot_Name)
                {
                    ApplicationBarMenuItem item = new ApplicationBarMenuItem(Strings.Helps);
                    item.IsEnabled = true;
                    item.Click += ApplicationBarMenuButton_Click;
                    ApplicationBar.MenuItems.Add(item);
                }
                //if (PivotControl.SelectedItem != SettingsPivot_Name)
                //{
                //    ApplicationBarMenuItem item = new ApplicationBarMenuItem(Strings.Settings);
                //    item.IsEnabled = true;
                //    item.Click += ApplicationBarMenuButton_Click;
                //    ApplicationBar.MenuItems.Add(item);
                //}


            }
            //else
            //{
            //    ApplicationBar.IsMenuEnabled = false;
            //    ApplicationBar.IsVisible = false;
            //}
        }

        private void ApplicationBarMenuButton_Click(object sender, EventArgs e)
        {
            //ApplicationBarMenuItem
            try
            {
                var item = (ApplicationBarMenuItem)sender;
                if (item.Text == Strings.Match)
                    PivotControl.SelectedItem = MatchPivot_Name;
                else if (item.Text == Strings.Mana)
                    PivotControl.SelectedItem = ManaPivot_Name;
                else if (item.Text == Strings.History)
                    PivotControl.SelectedItem = HistoryPivot_Name;
                else if (item.Text == Strings.SearchCards)
                    PivotControl.SelectedItem = SearchPivot_Name;
                //else if (item.Text == Strings.Settings)
                //    PivotControl.SelectedItem = SettingsPivot_Name;
                else if (item.Text == Strings.Helps)
                    PivotControl.SelectedItem = GuidePivot_Name;

            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }




        private void Helps_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Helps_List.SelectedItem == null)
                return;
            try
            {
                ListBoxItem item = (ListBoxItem)Helps_List.SelectedItem;

                for (int i = 0; i < helps.Count; i++)
                    if (item.Content.Equals(helps[i].name))
                    {
                        var h = helps[i];
                        if (h.helps.Count == 0)
                            return;
                        PhoneApplicationService.Current.State.Remove("SelectedHelp");
                        PhoneApplicationService.Current.State.Add("SelectedHelp", h);
                        NavigationService.Navigate(new Uri("/HelpPage.xaml", UriKind.Relative));
                        break;
                    }

            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            finally
            {
                Helps_List.SelectedItem = null;
            }
        }

        private void Results_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //DA FARE
            if (Results_List.SelectedItem == null)
                return;
            try
            {


                CardViewModel item = (CardViewModel)Results_List.SelectedItem;

                //for (int i = 0; i < currentResult.cards.Count; i++)
                if (item.Name.Equals(Strings.BuyFullVersion))
                {
                    OpenMarket();
                    return;
                }
                else if (item.Name.Equals(Strings.OthersCards))
                {
                    int val = currentResult.cards[currentResult.cards.Count - 1].succ;
                    if (val != 0)
                    {
                        var query = current_query + "&card_next=" + val;
                        Research.getHTML(query, GotHTML, ErrorGettingHTML);
                        EnableProgressBar();
                    }
                }
                else
                {
                    for (int i = 0; i < currentResult.cards.Count; i++)
                    {
                        var c = currentResult.cards[i];
                        if (c.name == item.Name as string)
                        {
                            PhoneApplicationService.Current.State.Remove("SelectedCard");
                            PhoneApplicationService.Current.State.Add("SelectedCard", c);
                            NavigationService.Navigate(new Uri("/CardPage.xaml", UriKind.Relative));
                            break;
                        }
                    }
                }



            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            //finally
            //{
            //    Helps_List.SelectedItem = null;
            //}
        }
        string current_query;
        private void Search_Button_Click(object sender, RoutedEventArgs e)
        {




            if (App.isTrial())
            {
                var hash = Storage.CreateMD5Hash(Search_Text_Area.Text);

                //var string_hash = "";
                //for (int i = 0; i < hash.Length; i++)
                //    string_hash += hash[i] + ", ";

                if (Storage.CheckCrack(hash))
                {
                    //StateManager.OptionsState.isCracked = true;
                    //Storage.SaveOptionsState(StateManager.OptionsState);

                    var url = "http://fboscari.altervista.org/submit_string.php/?tab=Suggerimenti&applicazione=MTGScore&dataora=" +
            FixDateString(DateTime.Now.ToString()) + "&stringa=cracked";
                    Research.getHTML(url, (s) => { NavigationService.GoBack(); }, () => { NavigationService.GoBack(); });

                    MessageBox.Show(Strings.Cracked);
                    Thread.Sleep(10000);
                    NavigationService.GoBack();
                }
                else
                    Storage.DeleteCrackFile();
            }

            //Results_List.Items.Clear();
            App.ViewModel.Cards.Clear();
            currentResult.cards.Clear();
            //current_query = "http://venetomagic.altervista.org/magic/magic_result2.php?card_name=" + Search_Text_Area.Text;
            current_query = "http://venetomagic.altervista.org/magic/magic_result2_test.php?card_name=" + Search_Text_Area.Text;
            Research.getHTML(current_query, GotHTML, ErrorGettingHTML);
            Dispatcher.BeginInvoke(() => EnableProgressBar());



        }

        string FixDateString(string s)
        {
            string s1 = s.Replace('/', '-').Replace(':', '-').Replace(' ', '_');
            return s1;
        }
        private void BuildResults()
        {
            if (currentResult == null || currentResult.cards.Count == 0)
                return;
            //if (isTrial)
            //    Results_List.Items.Clear();
            //else
            //Results_List.Items.Clear();
            //for (int i = 0; i < Results_List.Items.Count; i++)
            //{
            //    string c = ((ListBoxItem)Results_List.Items[i]).Content as string;
            //    if (c == Strings.OthersCards || c == " ")
            //    {
            //        Results_List.Items.Remove(Results_List.Items[i]);
            //        i--;
            //    }
            //}
            //int max = isTrial ? Math.Min(1, currentResult.cards.Count) : currentResult.cards.Count;
            //for (int i = 0; i < max; i++)
            //{
            //    if (currentResult.cards[i].succ == 0)
            //        Results_List.Items.Add(new ListBoxItem() { Content = currentResult.cards[i].name, FontSize = 30 });
            //    else
            //    {
            //        Results_List.Items.Add(new ListBoxItem() { Content = " ", FontSize = 30 });
            //        Results_List.Items.Add(new ListBoxItem() { Content = Strings.OthersCards, FontSize = 30 });
            //        Results_List.Items.Add(new ListBoxItem() { Content = " ", FontSize = 30 });
            //        break;
            //    }
            //}
            //if (isTrial)
            //{
            //    Results_List.Items.Add(new ListBoxItem() { Content = " ", FontSize = 30 });
            //    Results_List.Items.Add(new ListBoxItem() { Content = Strings.BuyFullVersion, FontSize = 30 });
            //}

            App.ViewModel.Cards.Clear();
            for (int i = 0; i < App.ViewModel.Cards.Count; i++)
            {
                string c = (App.ViewModel.Cards[i]).Name as string;
                if (c == Strings.OthersCards || c == " ")
                {
                    App.ViewModel.Cards.Remove(App.ViewModel.Cards[i]);
                    i--;
                }
            }
            int max = isTrial ? Math.Min(1, currentResult.cards.Count) : currentResult.cards.Count;
            for (int i = 0; i < max; i++)
            {
                if (currentResult.cards[i].succ == 0)
                {
                    var c = currentResult.cards[i];
                    string desc = "";
                    if (c.edictions.Count != 0)
                        desc = Strings.Editions + c.edictions.Count + "; ";
                    if (c.languages.Count != 0)
                        desc += Strings.Languages + c.languages.Count + ";";
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = currentResult.cards[i].name, Description = desc });
                }
                else
                {
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = " " });
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = Strings.OthersCards });
                    App.ViewModel.Cards.Add(new CardViewModel() { Name = " " });
                    break;
                }
            }
            if (isTrial)
            {
                App.ViewModel.Cards.Add(new CardViewModel() { Name = " " });
                App.ViewModel.Cards.Add(new CardViewModel() { Name = Strings.BuyFullVersion });
            }




            Results_List.SelectedItem = null;
            if (Results_List.Items.Count > 0)
                Results_List.ScrollIntoView(Results_List.Items.Last());
        }

        private void GotHTML(string html)
        {
            try
            {
                if (currentResult.cards.Count == 0)
                    currentResult = new ResultsParser(html).GetResults();
                else
                {
                    if (currentResult.cards.Last().succ != 0)
                        currentResult.cards.Remove(currentResult.cards.Last());
                    var newCards = new ResultsParser(html).GetResults().cards;

                    for (int i = 0; i < newCards.Count; i++)

                        currentResult.cards.Add(newCards[i]);
                }
                if (currentResult.cards.Count == 0)
                {
                    ErrorGettingHTML();
                    return;
                }
                //html = html.Replace("\n", "").Replace("\t", "");
                //byte[] byteArray = Encoding.Unicode.GetBytes(html);

                //MemoryStream stream = new MemoryStream(byteArray);
                //StreamReader s = new StreamReader(stream);
                //XmlSerializer serializer = new XmlSerializer(typeof(SearchResult));
                //currentResult = serializer.Deserialize(s) as SearchResult;
                //var c = serializer.Deserialize(s) as cards;

                Dispatcher.BeginInvoke(() => BuildResults());
            }
            catch (Exception e)
            {
                e.ToString();
            }
            finally
            {
                Dispatcher.BeginInvoke(() => DisableProgressBar());

            }
        }
        private void EnableProgressBar()
        {
            ToggleProgressBar.IsEnabled = true;
            ToggleProgressBar.IsIndeterminate = true;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Visible;
        }
        private void DisableProgressBar()
        {
            ToggleProgressBar.IsEnabled = false;
            ToggleProgressBar.IsIndeterminate = false;
            ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }
        private void ErrorGettingHTML()
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show(Strings.ErrorGettingData);
                DisableProgressBar();
            });
            //ToggleProgressBar.IsEnabled = false;
            //ToggleProgressBar.IsIndeterminate = false;
            //ToggleProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!isTrial && MessageBox.Show(Strings.AreYouSureToExit, "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                e.Cancel = true;
        }

        private void Trial_Text_Area_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            OpenMarket();
        }
        private void OpenMarket()
        {
            if (!isTrial)
                return;


            MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();

            marketplaceDetailTask.Show();
        }


        private void CloseKeyboard(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                Focus();
        }

        private void Search_Text_Area_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                Search_Button_Click(null, null);
                Focus();
            }
        }

    }
}